<?php

namespace App\Service\Activity;

use App\Helpers\AliyunUtil;
use App\Model\UserProfile;
use App\Service\BaseService;
use Hyperf\DbConnection\Db;

/**
 * 邀请有奖页面信息
 */
class InviteInfoService extends BaseService
{
    public function handle()
    {
        $inviteProfileId = $this->request->input('invite_code', '');
        $userProfile = UserProfile::getInfoByProfileId($inviteProfileId);
        $userId = $userProfile ? $userProfile->user_id : 0;
        return [
            'user_id' => $userId,
            //邀请码
            'invite_code' => $userProfile ? $userProfile->user_profile_id : 0,
            //好友充值奖励
            'reward_recharge' => 10,
            //好友提现奖励
            'reward_withdraw' => 10,
            //邀请规则
            'rules' => "邀请好友注册，并绑定邀请关系后，你将获得以下奖励:\n1、好友每次充值，你将获得充值金币金额10%的金币奖励； \n2、好友每次获得接听语聊收入，你将获得语聊收入到账金额10%的金币奖励； \n3、以上金币奖励发放至个人收入账户中，可以直接提现；",
            //海报地址
            'poster' => $this->getPoster($userId),
            //奖励记录
            'reward_list' => $this->getRewardList()
        ];
    }

    function getRewardList()
    {
        $users = UserProfile::where(['role' => UserProfile::ROLE_HOST])->orderBy(Db::raw('rand()'))->select(['nick_name'])->limit(10)->get()->toArray();
        $list = [];
        foreach ($users as $user) $list[] = "恭喜{$user['nick_name']}邀请好友加入后提成" . mt_rand(2, 10) . "元";
        return $list;
    }

    /**
     * 生成海报地址
     */
    function getPoster($userId=0)
    {
        $userProfile = UserProfile::getProfile($userId);
        $inviteCode = intval($userProfile->user_profile_id);
        if($userProfile->qrcode) return $userProfile->qrcode;

        //邀请下载链接
        $url = 'http://www.hudongailian.com/xinmi/register.html?invitecode='.$inviteCode;
        $qrCodeFileName = 'qrcode/poster_images_'.$userId."_".rand(1,99999);
        $urlbase  = AliyunUtil::IMG_HOST.'invite_bgqrcode03.jpg';
        $base64 = base64_encode($inviteCode) ;
        $text = "/watermark,text_{$base64},color_FFFFFF,shadow_80,t_100,g_se,x_200,y_246";

        if($inviteCode>0){
            $inviteLink = AliyunUtil::posterQrCode($url,$qrCodeFileName,$urlbase,180,30,10).$text;
        }else{
            $inviteLink = AliyunUtil::posterQrCode($url,$qrCodeFileName,$urlbase,180,30,10);//图片链接
        }
        $bgImg = $inviteLink;
        //更新用户信息
        if(!empty($userProfile->user_id)){
            UserProfile::updateInfo($userProfile->user_id,['qrcode'=>$bgImg]);
        }
        return $bgImg;
    }
}
